import Scene from './Scene.js'

const defAttr = () => ({
    //纹理对象
    texture: null,
    //帧缓冲区对象
    frameBuffer: null,
    //深度缓冲区对象
    depthBuffer: null,

    width: 1024,
    height: 1024,
});

export default class Frame extends Scene {
    constructor(attr) {
        super(Object.assign(defAttr(), attr));
        this._init();
    }

    _init() {
        const { gl } = this;
        this.texture = gl.createTexture();
        this.frameBuffer = gl.createFramebuffer();
        this.depthBuffer = gl.createRenderbuffer();
    }

    update() {
        const { gl, width, height } = this;
        const textureIndex = 0;
        this._createTextureBuffer(textureIndex);
        this._createFrameBuffer(textureIndex);
        this._createDepthBuffer();
        //设置渲染尺寸
        gl.viewport(0, 0, width, height);
    }
    updateOfView() {
        const { gl, width, height } = this;
        //设置渲染尺寸
        gl.viewport(0, 0, width, height);
    }

    reset() {
        const { gl } = this;
        const { canvas: { width, height } } = gl;
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        gl.bindRenderbuffer(gl.RENDERBUFFER, null);
        gl.bindTexture(gl.TEXTURE_2D, null);
        gl.viewport(0, 0, width, height);
    }

    draw([r, g, b, a] = [0, 0, 0, 1]) {
        this.update();
        super.draw([r, g, b, a]);
        this.reset();
    }

    drawView([r, g, b, a] = [0, 0, 0, 1]) {
        this.updateOfView();
        super.draw([r, g, b, a]);
    }

    //创建纹理贴图 Texture
    _createTextureBuffer(index) {
        const { gl, width, height, texture } = this;

        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
        gl.activeTexture(gl[`TEXTURE${index}`]);

        gl.bindTexture(gl.TEXTURE_2D, texture);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);//设置滤波器
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
    }
    //创建帧缓冲区 FrameBuffer
    _createFrameBuffer(index) {
        const { gl, texture, frameBuffer } = this;

        gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, index);
    }
    //创建深度缓冲区 depthBuffer
    _createDepthBuffer() {
        const { gl, width, height, depthBuffer } = this;
        gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
        gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);//配装深度缓冲区
        gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);//向缓冲区中添加渲染缓冲区
    }
}